package com.xindaoapp.happypet.activity;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.GradeAll;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.view.CircleImageView;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshBase.OnRefreshListener;
import com.xindaoapp.happypet.view.pulltorefresh.PullToRefreshListView;

@SuppressLint("NewApi")
public class GradeActivity extends BaseLoadAnimationAcitivity implements OnClickListener {
    @ViewInject(R.id.tittle_shop_cancel)
    private ImageView tittle_shop_cancel;
    @ViewInject(R.id.tittle_shop_content)
    private TextView tittle_shop_content;


    @ViewInject(R.id.grade_list)
    private PullToRefreshListView grade_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_grade);
        super.onCreate(savedInstanceState);
        ViewUtils.inject(this);
        initClick();
        initListView();
    }

    private int page = 1;

    private void initListView() {
        fillData(1);
        grade_list.setPullRefreshEnabled(true);
        grade_list.setScrollLoadEnabled(true);
        grade_list.setOnRefreshListener(new OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                if (grades != null && grades.size() > 0) {
                    grades.clear();
                }
                page = 1;
                fillData(page);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                page++;
                fillData(page);

            }
        });

        setLastUpdateTime();
    }

    private final List<com.xindaoapp.happypet.bean.GradeAll.Grades.GradeItem> grades =
            new ArrayList<com.xindaoapp.happypet.bean.GradeAll.Grades.GradeItem>();
    private GradeAdapter adapter;
    private boolean isFirst = true;

    public void fillData(int page) {
        RequestParams params = new RequestParams();
        params.put("page", String.valueOf(page));
        params.put("pageSize", Address.PAGECOMMONSIZE);
        // final ProgressHUD ProgressDialog = ProgressHUD.show(this, "正在加载...", true, true, null);
        AddClient.get(Address.GRADE, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, String content) {
                try {
                    isFirst = true;
                    onDataArrived(true);
                    GradeAll parse = JSON.parseObject(content, GradeAll.class);
                    if (parse.getStatus().equals("1")) {
                        List<com.xindaoapp.happypet.bean.GradeAll.Grades.GradeItem> info = null;
                        try {
                            info = parse.data.info;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        grades.addAll(info);
                        if (adapter == null) {
                            adapter = new GradeAdapter(grades);
                            grade_list.getRefreshableView().setAdapter(adapter);
                        } else {
                            adapter.notifyDataSetChanged();
                        }
                        if (Integer.parseInt(parse.data.count) < 15) {
                            grade_list.setPullRefreshEnabled(false);
                            grade_list.setScrollLoadEnabled(false);
                        }
                    }
                    onLoaded();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                onLoaded();
                if (isFirst) {
                    onDataArrived(false);
                    SetOnLoadFailListener(new OnLoadFailListener() {
                        @Override
                        public void onLoadFail() {
                            if (grades.size() > 0) {
                                grades.clear();
                            }
                            fillData(1);
                        }
                    });
                } else {
                    onDataArrived(true);
                }
                super.onFailure(error, content);
            }
        });
    }

    private class GradeAdapter extends BaseAdapter {
        private final List<com.xindaoapp.happypet.bean.GradeAll.Grades.GradeItem> info;

        public GradeAdapter(List<com.xindaoapp.happypet.bean.GradeAll.Grades.GradeItem> info) {
            super();
            this.info = info;
        }

        @Override
        public int getCount() {
            return info.size();
        }

        @Override
        public Object getItem(int position) {
            return info.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = View.inflate(GradeActivity.this, R.layout.grade_list_item, null);
                holder.good_name = (TextView) convertView.findViewById(R.id.good_name);
                holder.good_sell = (TextView) convertView.findViewById(R.id.good_sell);
                holder.good_surplus = (TextView) convertView.findViewById(R.id.good_surplus);
                holder.good_stock = (TextView) convertView.findViewById(R.id.good_stock);
                holder.user_touxiang =
                        (CircleImageView) convertView.findViewById(R.id.user_touxiang);
                holder.user_name = (TextView) convertView.findViewById(R.id.user_name);
                holder.content = (TextView) convertView.findViewById(R.id.content);
                holder.grade_time = (TextView) convertView.findViewById(R.id.grade_time);
                holder.grade_all = (CheckedTextView) convertView.findViewById(R.id.grade_all);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.good_name.setText(info.get(position).goods_name);
            holder.good_name.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(GradeActivity.this, ProductDetailActivity1.class);
                    intent.putExtra("productId", (info).get(position).goods_id);
                    startActivity(intent);
                }
            });
            holder.good_sell.setText(info.get(position).sold_number);
            holder.good_surplus.setText(info.get(position).comment_percent);
            if (info.get(position).goods_number == null) {
                holder.good_stock.setText("0");
            } else {
                holder.good_stock.setText(info.get(position).goods_number);
            }
            ImageLoader.getInstance().displayImage(info.get(position).user_logo,
                    holder.user_touxiang);
            holder.user_name.setText(info.get(position).user_name);

            if (info.get(position).content.length() > 53) {
                holder.grade_all.setText("查看全文");
            } else {
                holder.grade_all.setText("");
            }


            holder.content.setText(info.get(position).content);

            // if(holder.content.getLineCount()>3){
            // holder.grade_all.setVisibility(View.VISIBLE);
            // }else{
            // holder.grade_all.setVisibility(View.GONE);
            // }
            holder.grade_time.setText(info.get(position).add_time);
            holder.grade_all.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (holder.grade_all.isChecked()) {
                        holder.content.setMaxLines(3);
                        holder.grade_all.setChecked(false);
                    } else {
                        holder.content.setMaxLines(50);
                        holder.grade_all.setChecked(true);
                    }


                }
            });
            // if(holder.content.getLineCount()<3){
            // holder.grade_all.setVisibility(View.GONE);
            // }else{
            // holder.grade_all.setVisibility(View.VISIBLE);
            // }
            return convertView;
        }
    }
    class ViewHolder {
        TextView good_name; // 名字
        TextView good_sell; // 月销量
        TextView good_surplus; // 好评
        TextView good_stock; // 库存
        CircleImageView user_touxiang; // 头像
        TextView user_name; // 名字
        TextView content; // 评价内容
        TextView grade_time; // 评价时间
        CheckedTextView grade_all; // 查看全文
    }

    private void setLastUpdateTime() {
        String text = CommonUtil.formatPullToRefreshDate();
        grade_list.setLastUpdatedLabel(text);
    }

    private void onLoaded() {
        grade_list.onPullDownRefreshComplete();
        // grade_list.onPullUpRefreshComplete();
    }

    private void initClick() {
        tittle_shop_content.setText("好评如潮");
        tittle_shop_cancel.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tittle_shop_cancel:
                finish();
                break;
            default:
                break;
        }
    }
}
